package com.wdxx.demo.httpClient;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.http.util.TextUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * jdk11 网络请求
 */
public class WebUtils {

    /**
     * post 请求
     * @param url
     * @param params
     * @param headers
     * @return
     * @throws Exception
     */
    public static String doPost(String url, Map<String, String> params, Map<String, String> headers)throws Exception {
        String responseStr = "";
        if(null != url && url.length() > 0){
            HttpPost httpPost = new HttpPost(url);

            //加入请求头
            if(null != headers && headers.size() > 0){
                for(Map.Entry<String, String> entry : headers.entrySet()){
                    httpPost.addHeader(entry.getKey(), entry.getValue());
                }
            }

            //添加参数
            List<NameValuePair> paramsList = new LinkedList<>();
            if(null != params && params.size() > 0){
                for(Map.Entry<String, String> entry : params.entrySet()){
                    paramsList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
            }

            if(null != paramsList && paramsList.size() > 0){
                UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(paramsList, "UTF-8");
                httpPost.setEntity(entityParam);
            }

            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            // 执行请求
            response = httpClient.execute(httpPost);
            // 获得响应的实体对象
            String entityStr = "";
            HttpEntity entity = response.getEntity();
            if(null != entity){
                // 使用Apache提供的工具类进行转换成字符串
                entityStr = EntityUtils.toString(entity, "UTF-8");
            }
            responseStr = entityStr;
        }else{
            throw new Exception("url is null");
        }

        return responseStr;
    }

    /**
     * get 请求
     * @param url
     * @param params
     * @param headers
     * @return
     * @throws Exception
     */
    public static String doGet(String url, Map<String, String> params, Map<String, String> headers)throws Exception {
        String responseStr = "";
        if(null != url && url.length() > 0){
            /*
             * 由于GET请求的参数都是拼装在URL地址后方，所以我们要构建一个URL，带参数
             */
            URIBuilder uriBuilder = new URIBuilder(url);

            //添加参数
            List<NameValuePair> paramsList = new LinkedList<>();
            if(null != params && params.size() > 0){
                for(Map.Entry<String, String> entry : params.entrySet()){
                    paramsList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
            }

            //参数
            if(null != paramsList && paramsList.size() > 0)
                uriBuilder.setParameters(paramsList);


            // 根据带参数的URI对象构建GET请求对象
            HttpGet httpGet = new HttpGet(uriBuilder.build());

            //加入请求头
            if(null != headers && headers.size() > 0){
                for(Map.Entry<String, String> entry : headers.entrySet()){
                    httpGet.addHeader(entry.getKey(), entry.getValue());
                }
            }


            // 执行请求
            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = httpClient.execute(httpGet);
            // 获得响应的实体对象
            HttpEntity entity = response.getEntity();
            // 使用Apache提供的工具类进行转换成字符串
            responseStr = EntityUtils.toString(entity, "UTF-8");
//            System.out.println("responseStr --- > "+responseStr);
        }else{
            throw new Exception("url is null");
        }

        return responseStr;
    }

    public static String doPut(String url, String token, String jsonStr) {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPut httpPut = new HttpPut(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
        httpPut.setConfig(requestConfig);
        httpPut.setHeader("Content-type", "application/json");
        httpPut.setHeader("DataEncoding", "UTF-8");
        httpPut.setHeader("token", token);

        CloseableHttpResponse httpResponse = null;
        try {
            httpPut.setEntity(new StringEntity(jsonStr));
            httpResponse = httpClient.execute(httpPut);
            HttpEntity entity = httpResponse.getEntity();
            String result = EntityUtils.toString(entity);
            return result;
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * post 请求
     *
     * @param url
     * @param params
     * @param headers
     * @return
     * @throws Exception
     */
    public static String doPostPayload(String url, String params, Map<String, String> headers) throws Exception {
        String responseStr = "";
        if (null != url && url.length() > 0) {
            HttpPost httpPost = new HttpPost(url);

            //加入请求头
            if (null != headers && headers.size() > 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpPost.addHeader(entry.getKey(), entry.getValue());
                }
            }

            //添加参数
            StringEntity stringEntity = new StringEntity(params, "application/json", "utf-8");
            httpPost.setEntity(stringEntity);

            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            // 执行请求
            response = httpClient.execute(httpPost);
            // 获得响应的实体对象
            HttpEntity entity = response.getEntity();
            // 使用Apache提供的工具类进行转换成字符串
            String entityStr = EntityUtils.toString(entity, "UTF-8");
            responseStr = entityStr;
        } else {
            throw new Exception("url is null");
        }

        return responseStr;
    }

    public String post(String actionUrl, Map<String, String> params) throws IOException {

        String BOUNDARY = java.util.UUID.randomUUID().toString();
        String PREFIX = "--";
        String LINEND = "\r\n";
        String MULTIPART_FROM_DATA = "multipart/form-data";
        String CHARSET = "UTF-8";
        URL uri = new URL(actionUrl);
        HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
        conn.setReadTimeout(30 * 1000); // 缓存的最长时间
        conn.setDoInput(true);// 允许输入
        conn.setDoOutput(true);// 允许输出
        conn.setUseCaches(false); // 不允许使用缓存
        conn.setRequestMethod("POST");
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Charsert", "UTF-8");
        conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
        StringBuilder sb = new StringBuilder();
        if (params != null) {
            // 首先组拼文本类型的参数
            for (Map.Entry<String, String> entry : params.entrySet()) {
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINEND);
                sb.append("Content-Disposition: form-data; name=\""
                        + entry.getKey() + "\"" + LINEND);
                sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
                sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
                sb.append(LINEND);
                sb.append(entry.getValue());
                sb.append(LINEND);
            }

        }

        DataOutputStream outStream = new DataOutputStream(
                conn.getOutputStream());
        if (!TextUtils.isEmpty(sb.toString())) {
            outStream.write(sb.toString().getBytes());
        }
        // 请求结束标志
        byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
        outStream.write(end_data);
        outStream.flush();

        // 得到响应码
        int res = conn.getResponseCode();
        InputStream in = conn.getInputStream();
        if (res == 200) {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                buffer.append(line);
            }

//          int ch;
//          StringBuilder sb2 = new StringBuilder();
//          while ((ch = in.read()) != -1) {
//              sb2.append((char) ch);
//          }
            return buffer.toString();
        }
        outStream.close();
        conn.disconnect();
        return in.toString();
    }



    /**
     * 获取cookie
     * @param url
     * @param params
     * @param headers
     * @return
     * @throws Exception
     */
    public static String doPostCookie(String url, Map<String, String> params, Map<String, String> headers)throws Exception {
        String cookie = "";
        if(null != url && url.length() > 0){
            HttpPost httpPost = new HttpPost(url);

            //加入请求头
            if(null != headers && headers.size() > 0){
                for(Map.Entry<String, String> entry : headers.entrySet()){
                    httpPost.addHeader(entry.getKey(), entry.getValue());
                }
            }

            //添加参数
            List<NameValuePair> paramsList = new LinkedList<>();
            if(null != params && params.size() > 0){
                for(Map.Entry<String, String> entry : params.entrySet()){
                    paramsList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
            }

            if(null != paramsList && paramsList.size() > 0){
                UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(paramsList, "UTF-8");
                httpPost.setEntity(entityParam);
            }

            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            // 执行请求
            response = httpClient.execute(httpPost);
            // 获得响应的实体对象
            HttpEntity entity = response.getEntity();

            Header[] ssoResponseHeader = response.getHeaders("Set-Cookie");

            for (int i = 0;i < ssoResponseHeader.length;i++){
                String resCookie = ssoResponseHeader[i].getValue();
                if(resCookie.contains(".Asp")){
                    cookie = ssoResponseHeader[i].getValue();
                }
            }
        }else{
            throw new Exception("url is null");
        }

        return cookie;
    }


}
